<template>
  <div class="h-auto my-2 mb-2 py-2">
    <!-- 左右分栏布局 -->
    <a-row :gutter="5">
      <!-- 左侧：单位查询和表格 -->
      <a-col :span="12" class="">
        <div class="left-panel">
          <!-- 单位查询表单 -->
          <div class="unit-search-form">
            <BasicForm @register="registerForm" @submit="handleSubmit"></BasicForm>
          </div>

          <!-- 单位表格 -->
          <div class="unit-table-container">
            <BasicTable
                @register="registerTable"
                :data-source="tableData"
                size="small"
                :can-resize="true"
                :bordered="true"
                :striped="true"
                @row-click="onUnitRowClick"
                :custom-row="customRow"
            >
              <template #toolbar>
                <a-button type="primary" @click="onAddEpibolyUnit">新增单位</a-button>
              </template>
              <template #action="{ record }">
                <TableAction
                    :actions="[
                    {
                      icon: 'clarity:note-edit-line',
                      tooltip: '修改',
                      onClick: (e) => {
                        e?.stopPropagation?.(); // 阻止事件冒泡
                        onEditEpibolyUnit.bind(null, record)();
                      },
                    },
                    {
                      icon: 'ant-design:delete-outlined',
                      tooltip: '删除',
                      color: 'error',
                      onClick: (e) => {
                        e?.stopPropagation?.(); // 阻止事件冒泡
                      },
                      popConfirm: {
                        title: '是否确认删除',
                        confirm: () => onDeleteEpibolyUnit(record), // 保持原样
                      },
                    },
                    /*{
                      icon: 'ant-design:stop-outlined',
                      tooltip: '列入黑名单',
                      color: 'warning',
                      ifShow: () => Number(record.status) !== 3,
                      popConfirm: {
                        title: '确定将此单位列入黑名单吗？',
                        confirm: () => onAddToBlacklist(record), // 保持原样
                      },
                      onClick: (e) => {
                        e?.stopPropagation?.(); // 阻止事件冒泡
                      },
                    },*/
                    {
                      icon: 'ant-design:file-text-outlined',
                      tooltip: '证照管理',
                      color: 'success',
                      onClick: (e) => {
                        e?.stopPropagation?.(); // 阻止事件冒泡
                        handleUnitCertificateManagement( record);
                      },
                    },
                  ]"
                />
              </template>
            </BasicTable>
          </div>
        </div>
      </a-col>

      <!-- 右侧：员工表格 -->
      <a-col :span="12">
        <div class="right-panel">
          <div class="panel-header">
            <h3></h3>
            <div class="header-actions">
              <span v-if="selectedUnit" class="selected-unit-info">
                当前单位：{{ selectedUnit.unitname || '未选择' }}
              </span>
              <a-button
                  v-if="selectedUnit"
                  type="primary"
                  @click="onAddEmployee"
                  style="margin-left: 16px"
              >
                新增员工
              </a-button>
            </div>
          </div>
          <!-- 员工表格区域 -->
          <div class="employee-table-container">
            <div v-if="!selectedUnit" class="no-unit-selected">
              <a-empty description="请先点击左侧单位查看员工信息">
                <template #image>
                  <a-icon type="team" style="font-size: 64px; color: #ccc" />
                </template>
              </a-empty>
            </div>

            <BasicTable
                v-else
                @register="registerEmployeeTable"
                :data-source="employeeTableData"
                size="small"
                :can-resize="true"
                :bordered="true"
                :striped="true"
            >
              <template #action="{ record }">
                <TableAction
                    :actions="[
                    {
                      icon: 'clarity:note-edit-line',
                      tooltip: '修改员工',
                      onClick: onEditEmployee.bind(null, record),
                    },
                    {
                      icon: 'ant-design:delete-outlined',
                      tooltip: '删除员工',
                      color: 'error',
                      popConfirm: {
                        title: '是否确认删除该员工',
                        confirm: onDeleteEmployee.bind(null,record),
                      },
                    },
                    // 列入黑名单
                    {
                      icon: 'ant-design:stop-outlined',
                      tooltip: '列入黑名单',
                      color: 'warning',
                      ifShow: () => Number(record.status) !== 3,
                      popConfirm: {
                        title: '确定将此员工列入黑名单吗？',
                        confirm: onEmployeeAddToBlackList.bind(null,record),
                      },
                    },
                    {
                      icon: 'ant-design:file-text-outlined',
                      tooltip: '证照管理',
                      color: 'success',
                      onClick: handlePersonCertificateManagement.bind(null, record),
                    },
              /*      {
                      icon: 'ant-design:user-outlined',
                      tooltip: '员工详情',
                      color: 'info',
                      onClick: onViewEmployeeDetail.bind(record),
                    },*/
                  ]"
                />
              </template>
            </BasicTable>
          </div>
        </div>
      </a-col>
    </a-row>
    <!-- 新增或修改单位使用的弹出窗口 -->
    <AddOrUpdateEpibolyUnit
        @register="registerAddOrUpdateForm"
        @success="afterSuccess"
    ></AddOrUpdateEpibolyUnit>

    <!-- 新增或修改员工使用的弹出窗口（待实现） -->
    <AddOrUpdateEpibolyPerson
        @register="registerAddOrUpdatePersonForm"
        @success="afterEmployeeSuccess"
    ></AddOrUpdateEpibolyPerson>

    <!-- 证照管理抽屉 -->
    <CertificateManagementDrawer
        v-if="certificateDrawerVisible"
        :visible="certificateDrawerVisible"
        :type="certificateSourceData.type"
        :sourceId="certificateSourceData.sourceId"
        :sourceName="certificateSourceData.sourceName"
        :fixedParams="certificateSourceData.fixedParams"
        :defaultFormData="certificateSourceData.defaultFormData"
        :disabledQueryFields="certificateSourceData.disabledQueryFields"
        :enabledQueryFields="certificateSourceData.enabledQueryFields"
        :orgcode="organizationCode"
        @close="closeCertificateDrawer"
        @success="onCertificateSuccess"
    >
    </CertificateManagementDrawer>
  </div>
</template>

<script lang="ts">
import { useGlobSetting } from '/@/hooks/setting';
import { getUserOrganization } from '/@/api/ehs/organization';
const { globalProjectCode } = useGlobSetting();
import { defineComponent, onMounted, provide, ref, watch } from 'vue';
import { BasicTable, TableAction, useTable } from '/@/components/Table';
import { BasicForm, useForm } from '/@/components/Form';
import {
  deleteEpibolyPerson,
  deleteEpibolyUnit,
  addEpibolyUnitToBlack,
  getEpibolyPersonByUnitId,

  addEpibolyPersonToBlack
} from '/@/api/ehs/epiboly';
import {
  EpibolyUnitQueryConditionFormSchema,
  EpibolyUnitTableColumn,
  EpibolyPersonTableColumn,
} from '/src/views/ehs/epiboly/epiboly.data';
import { useMessage } from '/@/hooks/web/useMessage';
import { OperationTypeEnum } from '/@/enums/appEnum';
import { queryEpibolyUnit } from '/@/api/ehs/epiboly';
import { QcUnifyTransToChildProps } from '/#/QcUnify';
import AddOrUpdateEpibolyUnit from '/@/views/ehs/epiboly/AddOrUpdateEpibolyUnit.vue';
import SetProjectParam from '/@/views/project/project/SetProjectParam.vue';
import { useModal } from '/@/components/Modal';
import { EpibolyUnitQueryConditionDto } from '/@/api/ehs/model/epibolyModel';
import AddOrUpdateEpibolyPerson from '/@/views/ehs/epiboly/AddOrUpdateEpibolyPerson.vue';
import CertificateManagementDrawer from '/@/views/ehs/epiboly/CertificateManagementDrawer.vue';

//相关单位的弹出框
const [registerAddOrUpdateForm, { openModal: openAddOrUpdateForm }] = useModal();

// 注册员工弹窗
const [registerAddOrUpdatePersonForm, { openModal: openAddOrUpdateEmployeeForm }] = useModal();

//证照管理弹出框注册
const [registerCertificateModal, { openModal: openCertificateModal }] = useModal();

export default defineComponent({
  name: 'epibolyUnit',
  components: {
    CertificateManagementDrawer,
    AddOrUpdateEpibolyPerson,
    SetProjectParam,
    AddOrUpdateEpibolyUnit,
    TableAction,
    BasicForm,
    BasicTable,
  },

  setup() {

    const organizationCode = ref('');

    const { createMessage } = useMessage();

    //定义模块的名称，提供给子孙组件获取使用
    const moduleName = ref('相关方');
    provide('moduleName', moduleName);

    // 单位表格数据
    const tableData = ref([]);
    // 员工表格数据
    const employeeTableData = ref([]);
    // 当前选中的单位
    const selectedUnit = ref(null);

    // 操作类型
    const operationType = ref(OperationTypeEnum.ADD);
    // 模态框标题
    const moduleTitle = ref('相关单位');

    const moduleTitlePerson = ref('相关人员');
    // 当前编辑的记录
    const currentRecord = ref<Partial<EpibolyUnitDto>>({});

    //注册单位查询表单
    const [registerForm, { setFieldsValue, updateSchema, submit }] = useForm({
      labelWidth: 60,
      schemas: EpibolyUnitQueryConditionFormSchema,
      showResetButton: false,
    });

    // 注册单位表格
    const [registerTable, { reload, getForm }] = useTable({
      title: '相关单位',
      columns: EpibolyUnitTableColumn,
      rowClassName: (record) => {
        return selectedUnit.value?.unitid === record.unitid ? 'ant-table-row-selected' : '';
      },
      actionColumn: {
        width: 50,
        title: '操作',
        dataIndex: 'action',
        slots: { customRender: 'action' },
        fixed: 'right',
      },

      showIndexColumn: true,
      // 添加以下配置自定义序号列
      indexColumnProps: {
        width: 25, // 设置序号列宽度为 80px
        title: '序号', // 自定义序号列标题
      },
      showTableSetting: true,
    });

    // 注册员工表格
    const [registerEmployeeTable, { reload: reloadEmployeeTable }] = useTable({
      title: '相关人员',
      columns: EpibolyPersonTableColumn,
      actionColumn: {
        width: 60,
        title: '操作',
        dataIndex: 'action',
        slots: { customRender: 'action' },
        fixed: 'right',
      },
      showIndexColumn: true,
      // 添加以下配置自定义序号列
      indexColumnProps: {
        width: 15, // 设置序号列宽度为 80px
        title: '序号', // 自定义序号列标题
      },
      showTableSetting: true,
    });

    // 处理单位表单提交
    async function handleSubmit(values: any = {}) {
      //先对相关方单位表格数据赋值为空
      tableData.value = [];
      // 清空右侧选中状态
      selectedUnit.value = null;
      employeeTableData.value = [];

      //查看数据查询条件和赋值
      let queryConditionDto: EpibolyUnitQueryConditionDto = {
        orgcode: organizationCode.value,
        keywords: values['keywords'] || '',
        status: values['status'] || '',
      };
      //执行查询
      try {
        const res = await queryEpibolyUnit(queryConditionDto);
        if (res) {
          tableData.value = res;
        } else {
          tableData.value = [];
          createMessage.info('未查询到相关数据');
        }
      } catch (error) {
        createMessage.error('查询数据失败');
        console.error('查询相关方单位数据失败：', error);
      }
    }

    // 处理员工数据加载
    async function loadEmployeeData(unitRecord: Recordable) {
      if (!unitRecord || !unitRecord.unitid) {
        employeeTableData.value = [];
        return;
      }

      try {
        const res = await getEpibolyPersonByUnitId(unitRecord.unitid);
        employeeTableData.value = res || [];

        if (employeeTableData.value.length === 0){
          createMessage.info('暂无相关人员');
        }else{
          createMessage.success(`已加载 ${employeeTableData.value.length} 名员工信息`);
        }
      } catch (error) {
        console.error('加载员工数据失败:', error);
        createMessage.error('加载员工数据失败');
        employeeTableData.value = [];
      }
    }

    // 单位行点击事件
    function onUnitRowClick(record: Recordable) {
      selectedUnit.value = record;

      // 自动加载该单位的员工数据
      loadEmployeeData(record);
    }

    // 自定义行属性，添加点击效果
    function customRow(record: Recordable) {
      const isSelected = selectedUnit.value?.unitid === record.unitid;
      return {
        style: {
          cursor: 'pointer',
          backgroundColor: isSelected ? '#bae7ff' : '',
        },
        onClick: () => onUnitRowClick(record),
        class: isSelected ? 'selected-row' : '',
      };
    }

    // 处理新增单位按钮点击
    function onAddEpibolyUnit() {
      let propsData: QcUnifyTransToChildProps = {
        moduleName: moduleTitle.value,
        operateType: OperationTypeEnum.ADD,
        orgcode: organizationCode.value,
      };
      openAddOrUpdateForm(true, propsData);
    }

    // 处理编辑单位按钮点击
    function onEditEpibolyUnit(record: Recordable) {
      let propsData: QcUnifyTransToChildProps = {
        moduleName: moduleTitle.value,
        operateType: OperationTypeEnum.EDIT,
        data: record,
        orgcode: organizationCode.value,
      };
      if (record.unitid) {
        propsData.id = record.unitid;
      }
      openAddOrUpdateForm(true, propsData);
    }

    // 处理删除单位
    function onDeleteEpibolyUnit(record: Recordable) {
      deleteEpibolyUnit(record.unitid)
          .then((res) => {
            if (res == undefined && (res == null || Object.keys(res).length == 0)) {
              createMessage.success('删除成功。', 2);
              // 如果删除的是当前选中的单位，清空右侧
              if (selectedUnit.value?.unitid === record.unitid) {
                selectedUnit.value = null;
                employeeTableData.value = [];
              }
              afterSuccess();
            }
          })
          .catch((ex) => {
            createMessage.error(ex.msg);
          });
    }

    // 处理添加到黑名单
    function onAddToBlacklist(record: Recordable) {
      addEpibolyUnitToBlack(record.unitid)
          .then((res) => {
            if (res == undefined || res == null || Object.keys(res).length == 0) {
              createMessage.success('已成功将该单位列入黑名单', 2);
              afterSuccess();
            }
          })
          .catch((ex) => {
            createMessage.error(ex.msg || '添加黑名单失败');
          });
    }


    //添加抽屉控制变量
    const certificateDrawerVisible = ref(false);
    const certificateSourceData = ref({
      type: 'unit',
      sourceId: '',
      sourceName: '',
      fixedParams: {},
      defaultFormData: {},
      disabledQueryFields: [],
      enabledQueryFields: []
    });

    // 修改单位证照管理函数
    function handleUnitCertificateManagement(unitRecord) {

      certificateSourceData.value = {
        type: 'unit',
        sourceId: unitRecord.unitid,
        sourceName: unitRecord.unitname,
        // 预设查询条件
        fixedParams: {
          isepiboly: true,           // 强制勾选相关方
          holdtype: '1',             // 强制选择单位证照
          epiboly: unitRecord.unitid // 锁定查询该单位的证照
        },
        // 新增证照时的预填数据
        defaultFormData: {
          isepiboly: true,
          isperson: false,           // 单位证照
          holduserid: unitRecord.unitid,
          holdusername: unitRecord.unitname,
          orgcode: organizationCode.value
        },
        // 禁用的查询字段
        disabledQueryFields: ['isepiboly', 'holdtype', 'epiboly'],
        // 可操作的查询字段
        enabledQueryFields: ['keywords', 'status']
      };

      certificateDrawerVisible.value = true;
    }

    // 修改人员证照管理函数
    function handlePersonCertificateManagement(personRecord) {

      certificateSourceData.value = {
        type: 'person',
        sourceId: personRecord.id,
        sourceName: personRecord.personname || personRecord.name,
        // 预设查询条件
        fixedParams: {
          isepiboly: true,          // 强制勾选相关方
          holdtype: '2',            // 强制选择人员证照
          epiboly: personRecord.id  // 锁定查询该人员的证照
        },
        // 新增证照时的预填数据
        defaultFormData: {
          isepiboly: true,
          isperson: true,           // 人员证照
          holduserid: personRecord.id,
          holdusername: personRecord.personname || personRecord.name,
          orgcode: organizationCode.value
        },
        // 禁用的查询字段
        disabledQueryFields: ['isepiboly', 'holdtype', 'epiboly'],
        // 可操作的查询字段
        enabledQueryFields: ['keywords', 'status']
      };

      certificateDrawerVisible.value = true;
    }

    // 关闭证照管理抽屉
    function closeCertificateDrawer() {
      certificateDrawerVisible.value = false;
    }

    // 证照操作成功回调
    function onCertificateSuccess() {
      createMessage.success('证照操作成功');
      // 可以根据需要在这里执行其他刷新操作
    }


    // 员工操作相关函数
    function onAddEmployee() {
      if (!selectedUnit.value) {
        createMessage.warning('请先选择单位');
        return;
      }
      let propsData: QcUnifyTransToChildProps = {
        moduleName: moduleTitlePerson.value,
        operateType: OperationTypeEnum.ADD,
        unitId: selectedUnit.value.unitid,
        orgcode: organizationCode.value,
      };
      openAddOrUpdateEmployeeForm(true, propsData);
    }

    function onEditEmployee(record: Recordable) {
      let propsData = {
        moduleName: moduleTitlePerson.value,
        operateType: OperationTypeEnum.EDIT,
        data: record,
        id: record.id,
        unitId: selectedUnit.value.unitid,
        orgcode: organizationCode.value,
      };
      openAddOrUpdateEmployeeForm(true, propsData);
    }

    function onDeleteEmployee(record: Recordable) {
      deleteEpibolyPerson(record.id).then(() => {
        createMessage.success('员工删除成功');
        loadEmployeeData(selectedUnit.value);
      }).catch(ex => {
        createMessage.error(ex.msg || '删除员工失败');
      });
    }

    function onEmployeeAddToBlackList(record: Recordable) {
      addEpibolyPersonToBlack(record.id)
          .then((res)=>{
            if (res== undefined || res == null || Object.keys(res).length==0){
              createMessage.success('添加黑名单成功',2)
              //刷新员工数据
              if (selectedUnit.value){
                loadEmployeeData(selectedUnit.value)
              }
            }
          })
          .catch((ex)=>{
            createMessage.error(ex.msg || '添加黑名单失败')
          })
    }

    function onViewEmployeeDetail(record: Recordable) {
      console.log('查看员工详情:', record);
      // TODO: 打开员工详情弹窗或页面
    }

    //处理成功后调用
    function afterSuccess() {
      submit();
    }

    function afterEmployeeSuccess() {
      if (selectedUnit.value) {
        loadEmployeeData(selectedUnit.value);
      }
    }

    // 初始化
    onMounted(async () => {
      try {
        //获取用户组织信息
        const orgResult= await  getUserOrganization()
        if (orgResult?.orgcode){
          organizationCode.value=orgResult.orgcode;
        }else {
          console.warn('未获取到组织代码，使用默认值');
        }
      }catch (error){
        console.error('获取组织信息失败', error)
        createMessage.error('获取组织信息失败，使用默认配置')
      }

      await handleSubmit();
    });

    return {
      organizationCode,
      moduleName,
      registerForm,
      registerTable,
      registerEmployeeTable,
      registerAddOrUpdateForm,
      registerAddOrUpdatePersonForm,
      registerCertificateModal,
      tableData,
      employeeTableData,
      selectedUnit,
      moduleTitle,
      customRow,
      handleSubmit,

      //操作员工
      handlePersonCertificateManagement,
      onUnitRowClick,
      onAddEpibolyUnit,
      onEditEpibolyUnit,
      onDeleteEpibolyUnit,
      onEmployeeAddToBlackList,

      //操作单位
      handleUnitCertificateManagement,
      onAddEmployee,
      onEditEmployee,
      onDeleteEmployee,
      onViewEmployeeDetail,
      onAddToBlacklist,
      afterSuccess,
      afterEmployeeSuccess,

      // 添加证照抽屉相关
      certificateDrawerVisible,
      certificateSourceData,
      closeCertificateDrawer,
      onCertificateSuccess,
    };
  },
});
</script>

<style scoped lang="less">
.unit-employee-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 16px;
}

.layout-container {
  display: flex;
  flex: 1;
  gap: 16px;
  min-height: 600px;
}

.left-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: white;
  border-radius: 6px;
  padding: 16px;
}

.right-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: white;
  border-radius: 6px;
  padding: 16px;
}

.unit-search-form {
  margin-bottom: 16px;
  padding: 16px;
  background: #fafafa;
  border-radius: 6px;
}

.unit-table-container {
  flex: 1;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;

  h3 {
    margin: 0;
    font-size: 16px;
    font-weight: 500;
  }

  .header-actions {
    display: flex;
    align-items: center;
  }

  .selected-unit-info {
    color: #1890ff;
    font-size: 14px;
    font-weight: 500;
  }
}

.employee-table-container {
  flex: 1;

  .no-unit-selected {
    height: 400px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
